//
//  MapView.m
//  OrderFood
//
//  Created by xiaofang wang on 2018/10/27.
//  Copyright © 2018年 zhiyuan. All rights reserved.
//

#import "MapView.h"
#import "FGPSManager.h"
@interface MapView()<CLLocationManagerDelegate,GMSMapViewDelegate>
@property(nonatomic,strong)GMSMapView *mapView;//地图
@property(nonatomic,strong)GMSMarker *storeMarker;//大头针
@property(nonatomic,strong)GMSMarker *userMarker;//大头针
@property(nonatomic,strong)CLLocationManager *locationManager;//地图定位对象
@property(nonatomic,assign)CLLocationCoordinate2D myPosition;//骑手位置
@property(nonatomic,assign)CLLocationCoordinate2D storePosition;//商家位置
@property(nonatomic,assign)CLLocationCoordinate2D userPosition;//客户位置
@property(nonatomic,strong)UIView *alphaView;//距离背景
@property(nonatomic,strong)UILabel *distanceLb;//距离
@property(nonatomic,assign)OrderState orderState;//订单状态
@end
@implementation MapView
-(instancetype)initWithFrame:(CGRect)frame storePosition:(CLLocationCoordinate2D)storePosition userPosition:(CLLocationCoordinate2D)userPosition orderState:(OrderState)orderState{
    if (self = [super initWithFrame:frame]) {
        self.storePosition = storePosition;
        self.userPosition = userPosition;
        self.orderState = orderState;
        [self setUI];
    }
    return self;
}
-(void)setUI{
    
    //    camera可以理解为一个初始定位点，后面我们获得用户的位置之后，可以重新设置用户的位置为定位点。
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:22.290664
                                                            longitude:114.195304
                                                                 zoom:14];
    _mapView = [GMSMapView mapWithFrame:self.bounds camera:camera];
    _mapView.delegate = self;
    [_mapView setMinZoom:2 maxZoom:17];
    _mapView.mapType = kGMSTypeNormal;
    [self addSubview:self.mapView];
    _mapView.settings.compassButton = YES;
    _mapView.myLocationEnabled = YES;
    _mapView.settings.myLocationButton = YES;
    
    self.storeMarker = [[GMSMarker alloc] init];
    _storeMarker.position = self.storePosition;
    _storeMarker.tracksInfoWindowChanges = YES;
    _storeMarker.map = _mapView;
    _storeMarker.icon = [UIImage imageNamed:@"qu"];
    self.userMarker = [[GMSMarker alloc] init];
    _userMarker.position = self.userPosition;
    _userMarker.tracksInfoWindowChanges = YES;
    _userMarker.map = _mapView;
    _userMarker.icon = [UIImage imageNamed:@"song"];
    
    
    UIView *alphaView = [[UIView alloc] initWithFrame:CGRectMake(0, self.mh_height-30, SCREEN_WIDTH, 30)];
    alphaView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    [self addSubview:alphaView];
    self.alphaView = alphaView;
    UILabel *distanceLb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH-30, 30)];
    distanceLb.font = FONT(14);
    distanceLb.textColor = WHITECOLOR;
    distanceLb.text = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"distanceOftakefood", nil),@"100m"];
    [alphaView addSubview:distanceLb];
    self.distanceLb = distanceLb;
    //    定位，获取用户的位置，使用系统的CLLocationManager
    [self startLocation];
}
#pragma mark - GMSMapViewDelegate
//地图即将移动
- (void)mapView:(GMSMapView *)mapView willMove:(BOOL)gesture{
    
    
}
//在特定坐标点击手势后调用，但仅在未点击标记时调用。
- (void)mapView:(GMSMapView *)mapView didTapAtCoordinate:(CLLocationCoordinate2D)coordinate{
    
}

#pragma mark - 开始定位
- (void)startLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationManager = [[CLLocationManager alloc]init];
        self.locationManager.delegate = self;
        // 授权方式，如果在后台也需要定位，那就选择 requestAlwaysAuthorization。
        [self.locationManager requestAlwaysAuthorization];
        //控制定位精度,越高耗电量越
        self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
        self.locationManager.distanceFilter = 10.0f;// 默认是  否：kCLDistanceFilterNone;
        [self.locationManager startUpdatingLocation];
    }
}


//定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}
//定位成功经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *curLocation = [locations lastObject];
    // 通过location  或得到当前位置的经纬度
    CLLocationCoordinate2D curCoordinate2D = curLocation.coordinate;
    self.myPosition = curCoordinate2D;

    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:curCoordinate2D.latitude longitude:curCoordinate2D.longitude zoom:14];
    self.mapView.camera = camera;//这句话很重要很重要，将我们获取到的经纬度转成影像并赋值给地图的camera属性
    
    
    [self drawPolyline];

    //    [self.locationManager stopUpdatingLocation];//定位成功后停止定位
}
// 绘制线路图
-(void)drawPolyline{
    if (self.orderState == ReceiveState || self.orderState == GetFoodState) {
        GMSMutablePath * gmspath=[GMSMutablePath path];
        [gmspath addCoordinate:self.myPosition];
        [gmspath addCoordinate:self.storePosition];
        GMSPolyline *polyline = [GMSPolyline polylineWithPath:gmspath];
        polyline.strokeWidth = 3;
        polyline.strokeColor = quLineColor;
        polyline.map = self.mapView;
        
        GMSMutablePath * gmspath1=[GMSMutablePath path];
        [gmspath1 addCoordinate:self.storePosition];
        [gmspath1 addCoordinate:self.userPosition];
        GMSPolyline *polyline1 = [GMSPolyline polylineWithPath:gmspath1];
        polyline1.strokeWidth = 3;
        polyline1.strokeColor = songLineColor;
        polyline1.map = self.mapView;
        CGFloat distence = [self distanceBetweenOrderByFrom:self.myPosition to:self.storePosition];
        self.distanceLb.text = [NSString stringWithFormat:@"%@%0.fm",NSLocalizedString(@"distanceOftakefood", nil),distence];
    }else if (self.orderState == SendState || self.orderState == AbnomalState){
        
        GMSMutablePath * gmspath1=[GMSMutablePath path];
        [gmspath1 addCoordinate:self.storePosition];
        [gmspath1 addCoordinate:self.userPosition];
        GMSPolyline *polyline1 = [GMSPolyline polylineWithPath:gmspath1];
        polyline1.strokeWidth = 3;
        polyline1.strokeColor = songLineColor;
        polyline1.map = self.mapView;
        CGFloat distence = [self distanceBetweenOrderByFrom:self.storePosition to:self.userPosition];
        self.distanceLb.text = [NSString stringWithFormat:@"%@%0.fm",NSLocalizedString(@"distanceOfsendfood", nil),distence];
        if (self.orderState == AbnomalState) {
            self.alphaView.hidden = YES;
        }
    }else{
        self.alphaView.hidden = YES;
    }
}
//根据经纬度换算距离
-(double)distanceBetweenOrderByFrom:(CLLocationCoordinate2D)from to:(CLLocationCoordinate2D)to{
    CLLocation *curLocation = [[CLLocation alloc] initWithLatitude:from.latitude longitude:from.longitude];
    CLLocation *otherLocation = [[CLLocation alloc] initWithLatitude:to.latitude longitude:to.longitude];
    double  distance  = [curLocation distanceFromLocation:otherLocation];
    return  distance;
}


-(void)dealloc{
    self.mapView = nil;
    self.mapView.delegate = nil;
    self.locationManager = nil;
    self.locationManager.delegate = nil;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
